# 设置 PowerShell 的控制台输出编码为 UTF-8
# 这对于正确显示非 ASCII 字符至关重要
$OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::InputEncoding = [System.Text.Encoding]::UTF8

# 强制设置控制台的活动代码页为 UTF-8 (65001)
# 这是解决 Write-Host 中文乱码的关键一步
chcp 65001 > $null

# 初始化变量
$commitChanges = @()  # 数组存储每个提交的总变化行数
$commitDates = @()    # 数组存储每个提交的日期 (YYYY-MM-DD)
$currentAdd = 0
$currentDel = 0
$currentDate = $null

# 获取 git log 输出，包括日期和 numstat
$gitLogOutput = git log --pretty=format:"%H %ad" --date=short --numstat

# 逐行处理输出
foreach ($line in $gitLogOutput) {
    if ($line -match '^([0-9a-f]+) (\d{4}-\d{2}-\d{2})') {
        # commit 行: hash 和日期
        # 如果有当前提交的累加，添加到数组（应用过滤）
        if (($currentAdd -gt 0 -or $currentDel -gt 0) -and (($currentAdd + $currentDel) -lt 2500) -and $currentDate) {
            $commitChanges += ($currentAdd + $currentDel)
            $commitDates += $currentDate
        }
        # 更新当前日期并重置累加
        $currentDate = $matches[2]
        $currentAdd = 0
        $currentDel = 0
    } elseif ($line -match '^\d+\s+\d+\s+.*' -or $line -match '^\-\s+\-\s+.*') {
        # 使用正则表达式匹配数字或 '-'
        $matchCases = $line | Select-String -Pattern '(\d+|-)\s+(\d+|-)\s+.*'

        if ($matchCases) {
            # 提取匹配到的数字或 '-'
            $parts = $matchCases.Matches[0].Groups[0].Value.Split([char[]]"`t", [System.StringSplitOptions]::RemoveEmptyEntries)

            # 确保 parts 数组至少有两个元素 (新增行数和删除行数)
            if ($parts.Length -ge 2) {
                $add = $parts[0]
                $del = $parts[1]

                # 处理二进制文件的情况，将 '-' 视为 0
                if ($add -eq '-') { $add = 0 }
                if ($del -eq '-') { $del = 0 }

                # 仅当该文件变化 <1500 时累加
                if (([int]$add + [int]$del) -lt 2500) {
                    $currentAdd += [int]$add
                    $currentDel += [int]$del
                }
            }
        }
    }
}

# 添加最后一个提交的变化
if (($currentAdd -gt 0 -or $currentDel -gt 0) -and (($currentAdd + $currentDel) -lt 1500) -and $currentDate) {
    $commitChanges += ($currentAdd + $currentDel)
    $commitDates += $currentDate
}

# 计算总变化、平均值和中位数
$totalChanges = ($commitChanges | Measure-Object -Sum).Sum
$commitCount = $commitChanges.Count

if ($commitCount -gt 0) {
    $average = [math]::Round($totalChanges / $commitCount, 2)

    # 计算中位数
    $sortedChanges = $commitChanges | Sort-Object
    if ($commitCount % 2 -eq 1) {
        $median = $sortedChanges[[math]::Floor($commitCount / 2)]
    } else {
        $mid = $commitCount / 2
        $median = [math]::Round(($sortedChanges[$mid - 1] + $sortedChanges[$mid]) / 2, 2)
    }
} else {
    $average = 0
    $median = 0
}

# 新增：按日期分组统计
$dailyStats = @{}
for ($i = 0; $i -lt $commitChanges.Count; $i++) {
    $date = $commitDates[$i]
    $changes = $commitChanges[$i]
    if (-not $dailyStats.ContainsKey($date)) {
        $dailyStats[$date] = @{ Count = 0; TotalChanges = 0 }
    }
    $dailyStats[$date].Count += 1
    $dailyStats[$date].TotalChanges += $changes
}

# 输出汇总
Write-Host "Total Commits: $commitCount"
Write-Host "Total Changes: $totalChanges"
Write-Host "Average Changes per Commit: $average"
Write-Host "Median Changes per Commit: $median"

# 输出每日统计（只显示有提交的日期，按日期降序排序）
Write-Host "`nDaily Commit Stats (only days with commits): $($dailyStats.Count) days"
$sortedDates = $dailyStats.Keys | Sort-Object -Descending
foreach ($date in $sortedDates) {
    $stats = $dailyStats[$date]
    Write-Host "Date: $date - Commits: $($stats.Count) - Total Changes: $($stats.TotalChanges)"
}

Write-Host "`nDaily Commit times and changes : $([math]::Floor($commitCount / $dailyStats.Count)) / $([math]::Floor($totalChanges / $dailyStats.Count))"
